import axios from "axios";
import ip from "ip";
import { SvnHolder } from "../core/SvnHolder.js";
import { Hudson } from "./hudson.js";
import moment from "moment";

declare type IWxRobotMsgPayload = {
    chatid: string
} & ({
    mention?: string,
    payload: {
        msgtype: 'text',
        text: {
            content: string
        }
    }
} | {
    payload: {
        msgtype: 'markdown',
        markdown: {
            content: string
        }
    }
} | {
    payload: {
        msgtype: 'news',
        news: {
            articles: {
                title: string
                description?: string
                url: string
                picurl?: string
            }[]
        }
    }
});

export class Alert {

    private static ins: Alert;
    public static get Instance(): Alert {
        if(!Alert.ins) Alert.ins = new Alert();
        return Alert.ins;
    }

    private chatid: string | null = null;
    public setChatId(chatid: string): void {
        this.chatid = chatid;
    }

    public async sendBuildFailureAlert(msg: string): Promise<void> {        
        if (!this.chatid) return;
        const startUser = await Hudson.getStartUser();
        const theIp = ip.address();
        const content = `# <font color=\"warning\">${Hudson.getJobName()} #${Hudson.getBuildNumber()} 失败</font>
>发起人：@${startUser}
>时间：${moment().format(moment.HTML5_FMT.TIME)}
>${msg} 
>点击查看日志：[构建日志](http://${theIp}:8080/hudson/job/${Hudson.getJobName()}/${Hudson.getBuildNumber()}/consoleText)`;
    
        // 先群发消息
        await this.sendRobotMsg('markdown', content);
    }

    public async alertErrorFile(file: string): Promise<void> {
        if (!this.chatid) return;

        const info = await SvnHolder.Instance.svnClient.info([file], { showItem: 'last-changed-author' });
        const touser = info.trim();
        await this.sendRobotMsg('text', '文件错误，速改！\n' + file, touser);
    }
    
    public async sendRobotMsg(type: 'text' | 'markdown', msg: string, mention?: string): Promise<void> {
        if (!this.chatid) return;
        let payload: IWxRobotMsgPayload;
        if (type == 'text') {
            payload = {
                chatid: this.chatid,
                mention,
                payload: {
                    msgtype: 'text',
                    text: {
                        content: msg
                    }
                }
            }
        } else {
            payload = {
                chatid: this.chatid,
                payload: {
                    msgtype: 'markdown',
                    markdown: {
                        content: msg
                    }
                }
            }
        }
        await this.sendRobotMsgInternal(payload);
    }
    
    private async sendRobotMsgInternal(payload: IWxRobotMsgPayload): Promise<void> {
        const result = await axios.post<string>('http://builder.fygame.com:3000/api/app/robotmsg', { data: payload }, { timeout: 3000, proxy: false }).catch((e) => {});
        if (result?.data !== 'ok') {
            console.error('robot msg sent failed:', payload);
        }
    }
}